<template>
  <n-card :bordered="false">
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              :show-feedback="false"
              label-placement="left"
              :label-width="80" @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="订单状态:">
          <n-space>
            <n-button size="small" :type="search_param.status==null && search_param.payStatus==null?'primary':'default'"
                      @click="handelSelectSearchStatus(null,null)">全部
            </n-button>
            <n-button size="small" :type="search_param.payStatus==0?'primary':'default'"
                      @click="handelSelectSearchStatus(0,null)">未支付
            </n-button>
            <n-button size="small" :type="search_param.payStatus==1?'primary':'default'"
                      @click="handelSelectSearchStatus(1,null)">已支付
            </n-button>
            <n-button size="small" :type="search_param.status==0?'primary':'default'"
                      @click="handelSelectSearchStatus(null,0)">正常
            </n-button>
            <n-button size="small" :type="search_param.status==1?'primary':'default'"
                      @click="handelSelectSearchStatus(null,1)">正在进行
            </n-button>
            <n-button size="small" :type="search_param.status==2?'primary':'default'"
                      @click="handelSelectSearchStatus(null,2)">已完成
            </n-button>
            <n-button size="small" :type="search_param.status==9?'primary':'default'"
                      @click="handelSelectSearchStatus(null,9)">已取消
            </n-button>
          </n-space>
        </n-form-item>
        <n-form-item label="创建时间:">
          <n-space>
            <n-button size="small" :type="orderTime==null?'primary':'default'"
                      @click="handelSelectSearchTime(null)">全部
            </n-button>
            <template v-for="item in orderTimeOption">
              <n-button size="small" :type="orderTime==item.value?'primary':'default'"
                        @click="handelSelectSearchTime(item.value)">{{ item.label }}
              </n-button>
            </template>
            <template v-if="orderTime=='other'">
              <n-date-picker :default-value="customDate" size="small" style="width: 280px" type="daterange"
                             @confirm="handelCustomDate" clearable/>
            </template>
          </n-space>
        </n-form-item>
        <n-form-item label="&nbsp;">
          <n-space>
            <n-input v-model:value="search_param.key" style="width: 320px"
                     placeholder="请输入订单号、姓名、电话查询"
                     clearable/>
            <search-button-group @submit="handleSubmitSearch"
                                 @reset="handleResetSearch"/>
          </n-space>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="order/list">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['order:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
    <n-modal v-model:show="addEditModel"
             :title="addEditForm.id?'修改订单':'新增订单'" :mask-closable="false"
             :show-icon="false" preset="dialog" style="width: 1200px" @after-leave="closeAddEditModel">
      <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
              label-placement="left" :label-width="80">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="6" label="姓名" path="userName">
            <n-input v-model:value="addEditForm.userName" placeholder="用户姓名" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="手机号码" path="phone">
            <n-input v-model:value="addEditForm.phone" maxlength="11" placeholder="用户手机号码" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="性别" path="sex">
            <n-radio-group v-model:value="addEditForm.sex" name="gender">
              <n-space>
                <n-radio :value="1" label="男"/>
                <n-radio :value="2" label="女"/>
              </n-space>
            </n-radio-group>
          </n-form-item-gi>
          <n-form-item-gi :span="6" v-if="addEditForm.id" label="订单号" path="sn">
            {{ addEditForm.sn }}
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="6" label="微信用户" path="userId">
            <n-select v-model:value="addEditForm.userId" :options="usersOptions" :render-label="renderUserLabel"
                      :render-tag="renderSingleSelectTag" filterable placeholder="请选择微信用户" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="年级" path="grade">
            <n-select v-model:value="addEditForm.grade" :options="gradeOption" value-field="key"
                      @update:value="getCourse" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="科目" path="courseId">
            <n-select v-model:value="addEditForm.courseId" :options="courseOption" value-field="key" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="课酬" path="price">
            <n-input-group>
              <n-input v-model:value="addEditForm.price"/>
              <n-input-group-label>/每小时</n-input-group-label>
            </n-input-group>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="地区" path="county">
            <n-space>
              <n-select v-model:value="addEditForm.province" :options="provinceOption"
                        @update:value="getCityOption" style="width: 170px" clearable/>
              <n-select v-model:value="addEditForm.city" :options="cityOptions"
                        @update:value="getCountyOption"
                        style="width: 140px" clearable/>
              <n-select v-model:value="addEditForm.county" :options="countyOptions" style="width: 130px"
                        clearable/>
            </n-space>
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="地址" path="address">
            <n-input v-model:value="addEditForm.address"
                     placeholder="地址" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="门派号" path="house">
            <n-input v-model:value="addEditForm.house"
                     placeholder="门派号" clearable/>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="24" label="情况" path="situation">
            <n-input v-model:value="addEditForm.situation"
                     placeholder="学员情况"
                     type="textarea"
                     size="small"
                     :autosize="{minRows: 3,maxRows: 3}"
            />
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="15" label="授课时间" path="res">
            <n-space>
              <n-radio-group v-model:value="addEditForm.res" name="radiobuttongroup1">
                <n-radio-button size="small" :value="0" label="每周一次"/>
              </n-radio-group>
              <n-checkbox-group v-model:value="addEditForm.day">
                <n-space style="margin-top: 5px;">
                  <n-checkbox :value="1" label="周一"/>
                  <n-checkbox :value="2" label="周二"/>
                  <n-checkbox :value="3" label="周三"/>
                  <n-checkbox :value="4" label="周四"/>
                  <n-checkbox :value="5" label="周五"/>
                  <n-checkbox :value="6" label="周六"/>
                  <n-checkbox :value="7" label="周日"/>
                </n-space>
              </n-checkbox-group>
            </n-space>
          </n-form-item-gi>
          <n-form-item-gi :span="4" label="每次时间" path="appTime">
            <n-input-number v-model:value="addEditForm.appTime" :show-button="false" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="5" label="总时间" path="totalTime">
            <n-input-group>
              <n-input-number v-model:value="addEditForm.totalTime" :show-button="false" clearable/>
              <n-input-group-label>小时</n-input-group-label>
            </n-input-group>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="6" label="教师性别" path="tSex">
            <n-radio-group v-model:value="addEditForm.tSex" name="tSexGender">
              <n-space>
                <n-radio :value="1" label="男"/>
                <n-radio :value="2" label="女"/>
                <n-radio :value="3" label="均可"/>
              </n-space>
            </n-radio-group>
          </n-form-item-gi>
          <n-form-item-gi :span="18" label="情况" path="tSituation">
            <n-input v-model:value="addEditForm.tSituation"
                     placeholder="教师情况" clearable/>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="6" label="支付状态" path="payStatus">
            <n-switch :round="false" v-model:value="addEditForm.payStatus" :checked-value="1" :unchecked-value="0">
              <template #checked>
                已支付
              </template>
              <template #unchecked>
                未支付
              </template>
            </n-switch>
          </n-form-item-gi>
          <n-form-item-gi :span="18" label="状态" path="status">
            <n-radio-group v-model:value="addEditForm.status" name="statusGroup">
              <n-space>
                <n-radio :value="0" label="正常"/>
                <n-radio :value="1" label="正在进行"/>
                <n-radio :value="2" label="完成"/>
                <n-radio :value="9" label="取消"/>
              </n-space>
            </n-radio-group>
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="()=>(addEditModel=false)">取消</n-button>
          <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
  <!--派遣教师-->
  <n-modal v-model:show="dispatchReplaceModel"
           :title="dispatchReplaceForm.hasSend?'更换'+dispatchReplaceModelTitle:'派遣'+dispatchReplaceModelTitle"
           :mask-closable="false"
           :show-icon="false" preset="dialog" style="width: 740px" @after-leave="closeDispatchReplace">
    <n-form ref="dispatchReplaceFormRef" :model="dispatchReplaceForm" require-mark-placement="left"
            label-placement="left" :show-feedback="false">
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi :span="8" label="订单号:">
          {{ dispatchReplaceForm.orderSn }}
        </n-form-item-gi>
        <n-form-item-gi :span="8" label="姓名:">
          {{ dispatchReplaceForm.userName }}
        </n-form-item-gi>
        <n-form-item-gi :span="8" label="电话:">
          {{ dispatchReplaceForm.phone }}
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi :span="8" label="年级:">
          {{ dispatchReplaceForm.gradeName }}
        </n-form-item-gi>
        <n-form-item-gi :span="8" label="分类:">
          {{ dispatchReplaceForm.classifyName }}
        </n-form-item-gi>
        <n-form-item-gi :span="8" label="课程:">
          {{ dispatchReplaceForm.courseName }}
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi :span="16" label="地址:">
          {{ dispatchReplaceForm.provinceName }}{{ dispatchReplaceForm.cityName }}{{ dispatchReplaceForm.countyName }}{{ dispatchReplaceForm.address }}
        </n-form-item-gi>
        <n-form-item-gi :span="8" label="门牌号:">
          {{ dispatchReplaceForm.house }}
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="24" :x-gap="24" v-if="dispatchReplaceForm.hasSend">
        <n-form-item-gi :span="16" label="已派遣:">
          {{ dispatchReplaceForm.alreadyTeachName }}
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi :span="8" label="课酬:">
          {{ dispatchReplaceForm.price }}元/小时
        </n-form-item-gi>
        <n-form-item-gi :span="8" label="教师性别:">
          {{ dispatchReplaceForm.tSex === 1 ? '男' : dispatchReplaceForm.tSex === 2 ? '女' : '均可' }}
        </n-form-item-gi>
      </n-grid>
    </n-form>
    <n-divider/>
    <n-space>
      <n-input-group>
        <n-input v-model:value="dispatchReplaceSearch.name" placeholder="输入教师姓名或电话查询"
                 :style="{ width: '100%' }" clearable/>
        <n-button type="primary" @click="getTeacherList">
          搜索
        </n-button>
      </n-input-group>
      <n-button @click="()=>(dispatchReplaceForm.tId=null,dispatchReplaceForm.checkedTId=[])">取消选择</n-button>
    </n-space>
    <n-data-table class="m-t-10"
                  :columns="drColumns"
                  :row-key="(row:Recordable) => row.id"
                  :data="drData"
                  :checked-row-keys="dispatchReplaceForm.checkedTId"
                  :pagination="false"
                  :max-height="250" size="small"
                  @update:checked-row-keys="checkedTeacherForOrder"
    />
    <template #action>
      <n-space>
        <n-button @click="()=>(dispatchReplaceModel=false)">取消</n-button>
        <n-button type="primary" :loading="dispatchHandelSubmitLoading" @click="submitDispatchReplace">确定
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>
<script setup lang="ts">
import {ref, reactive, h, computed, onBeforeMount, watch} from 'vue';
import SearchButtonGroup from '@components/SearchButtonGroup';
import {
  SelectOption,
  NTag,
  NPopconfirm,
  NEllipsis,
  FormInst,
  NIcon,
  CascaderOption,
  NAvatar,
  NText,
  TreeSelectOption,
  NSwitch, FormItemRule, useMessage, NImage
} from 'naive-ui';
import DateFns from '@/util/dateFns.ts'
import DataTable from '@components/DataTable';
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {AddSharp} from "@vicons/material";
import {delRequest, getRequest, postPutRequest} from "@/api/data.ts";
import {Config} from "@/config";


const message = useMessage()

const orderTimeOption = ref<SelectOption[]>([
  {
    label: '今天',
    value: 'today',
  }, {
    label: '昨天',
    value: 'yesterday',
  }, {
    label: '最近7天',
    value: '7days',
  }, {
    label: '最近30天',
    value: '30days',
  }, {
    label: '本月',
    value: 'month',
  }, {
    label: '本年',
    value: 'year',
  }, {
    label: '自定义',
    value: 'other',
  }
  //
])
const orderTime = ref<string | number | undefined | null>(null);
const usersOptions = ref<SelectOption[]>([]);
const reginData = ref<CascaderOption[]>([]);

const provinceOption = computed(() => {
  return reginData.value.map((item): CascaderOption => ({
    label: item.label,
    value: item.value
  }));
})
const cityOptions = ref<SelectOption[] | undefined>([]);
const countyOptions = ref<SelectOption[] | undefined>([]);
const gradeOption = ref<SelectOption[]>([]);//年级
const courseOption = ref<SelectOption[]>([]);//科目
//自定义默认日期
const customDate = computed(() => {
  const today = new Date();
  const startDate = new Date(today.getFullYear(), 0, 1); // 本年的第一天
  const endDate = new Date(today.getFullYear(), 11, 31, 23, 59, 59); // 本年的最后一天
  return [startDate.getTime(), endDate.getTime()];
})
const search_param = ref({
  key: null,
  status: <number | null>null,
  payStatus: <number | null>null,
  start: <number | string | null | any>null,
  end: <number | string | null | any>null,
})
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '订单号',
    key: 'sn',
    width: 190,
  }, {
    title: '用户信息',
    key: 'userName',
    width: 150,
    render(row: { userName: string, phone: string }) {
      return h('div', {style: {width: '100%'}}, {
        default: () => (
            [h(NEllipsis, {style: {display: 'block'}}, {default: () => (row.userName)}),
              h('div', null, {default: () => (row.phone)})
            ])
      })
    }
  }, {
    title: '课程信息',
    key: 'money',
    width: 130,
    render(row: { courseName: string, classifyName: string, gradeName: string }) {
      return h('div', {style: {width: '100%'}}, {
        default: () => (
            [h(NEllipsis, {style: {display: 'block'}}, {default: () => (row.courseName)}),
              h('div', null, {default: () => (row.classifyName + '/' + row.gradeName)})
            ])
      })
    }
  }, {
    title: '地址',
    key: 'address',
    render(row: { provinceName: string, cityName: string, countyName: string, address: string, house: string }) {
      const fullAddress: string = row.provinceName + row.cityName + row.countyName + row.address + row.house;
      return h('span', null, {default: () => (fullAddress)})
    }
  }, {
    title: '课时(小时)',
    key: 'appTime',
    width: 100,
    align: 'center',
    render(row: { appTime: string | number }) {
      const appTimeText = row.appTime + '小时';
      return h('span', null, {default: () => (appTimeText)})
    }
  }, {
    title: '教师性别',
    key: 'tSex',
    width: 100,
    align: 'center',
    render(row: { tSex: boolean | number }) {
      const genderText = row.tSex == 1 ? '男' : row.tSex == 2 ? '女' : '均可';
      return h('span', null, {default: () => (genderText)})
    }
  }, {
    title: '课酬',
    key: 'price',
    width: 100,
    render(row: { price: string }) {
      const priceText = row.price + '元/小时';
      return h('span', null, {default: () => (priceText)})
    }
  }, {
    title: '支付状态',
    key: 'status',
    width: 90,
    align: 'center',
    render(row: { payStatus: boolean | number }) {
      const enabled_color: any = row.payStatus ? 'success' : 'warning';
      const enabled_text = row.payStatus ? '支付' : '未支付';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 90,
    align: 'center',
    render(row: { status: boolean | number }) {
      let enabled_color: string | any;
      let enabled_text: string;
      switch (row.status) {
        case 0:
          enabled_text = '正常';
          enabled_color = 'default'
          break;
        case 1:
          enabled_text = '正在进行';
          enabled_color = 'info'
          break;
        case 2:
          enabled_text = '完成';
          enabled_color = 'success'
          break;
        case 9:
          enabled_text = '取消';
          enabled_color = 'error'
          break;
      }
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  }, {
    title: '派遣教师',
    key: 'teacher',
    width: 100,
    render(row: { teacher: { name: string } }) {
      let teachName: string = ''
      if (row.teacher) {
        teachName = row.teacher.name;
      }
      return h('span', null, {default: () => (teachName)})
    }
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  },
]);
//操作列
const actionColumn = reactive({
  width: 170,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['order:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前订单吗？',
          },
          permission: ['order:del']
        },
      ],
      dropDownActions: [
        {
          label: record.sendTeacher == 1 ? '更换教师' : '派遣教师',
          // @ts-ignore
          key: 'sendTeacher',
          permission: ['order:send:teach']
        },
      ],
      select: (key: string) => {
        if (key == 'sendTeacher') {
          dispatchReplaceTeacher(record)
        }
      }
    });
  },
});
//表单
const addEditModel = ref<boolean>(false);
const handelSubmitLoading = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);

//const isEdit=ref<boolean>(false);
interface addEditFormItem {
  id?: number,
  sn?: string | null,
  userId?: number | null,
  userName?: string | null,
  phone?: string | null,
  grade?: number | null,
  gradeName?: string | null,
  courseId?: number | null,
  courseName?: string | null,
  classifyName?: string | null,
  sex?: number | null,
  situation?: string | null,
  province?: number | null,
  provinceName?: string | null,
  city?: number | null,
  cityName?: string | null,
  county?: number | null,
  countyName?: string | null,
  address?: string | null,
  house?: string | null,
  payStatus?: number | null,
  status?: number | null,
  tSex?: number | null,
  price?: number | null,
  tSituation?: string | null,
  res?: number | null,
  day?: string | null,
  appTime?: number | null,
  totalTime?: number | null,
  remainder?: number | null,
}

const addEditForm = ref<addEditFormItem>({
  id: 0,
  sn: null,
  userId: null,
  userName: null,
  phone: null,
  grade: null,
  gradeName: null,
  courseId: null,
  courseName: null,
  classifyName: null,
  sex: 1,
  situation: null,
  province: null,
  provinceName: null,
  city: null,
  cityName: null,
  county: null,
  countyName: null,
  address: '',
  house: '',
  payStatus: 0,
  status: 0,
  tSex: 1,
  price: null,
  tSituation: null,
  res: 0,
  day: null,
  appTime: null,
  totalTime: null,
  remainder: null,
})
const addEditFormRules = computed(() => {
  return {
    userName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写用户姓名'
    },
    phone: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写用户电话号码'
    },
    sex: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择用户性别'
    },
    userId: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择微信用户'
    },
    grade: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择年级'
    },
    courseId: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择科目'
    },
    price: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写课酬'
    },
    county: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择地区'
    }, address: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写地址'
    }, house: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写门牌号'
    },
    res: {
      required: true,
      trigger: ['blur', 'change'],
      //  message: '请选择授课时间'
      asyncValidator: (_rule: FormItemRule, value: string) => {
        return new Promise<void>((resolve: any, reject: any) => {
          if (value == null) {
            reject(Error('请选择授课时间'))
          } else {
            resolve();
          }
        })
      }
    },

    appTime: {
      type: 'number',
      required: true,
      trigger: ['blur', 'input'],
      message: '请写每次时间'
    },
    totalTime: {
      type: 'number',
      required: true,
      trigger: ['blur', 'input'],
      message: '请写总时间'
    },
  }
})

//订单派遣教师和更换教师
interface dispatchReplace {
  orderId: number | null,//订单id
  orderSn: string | null,//订单号
  userName: string | null,//用户姓名
  phone: string | null,//用户电话
  courseName: string | null,//课程名称
  classifyName: string | null,//课程分类名称
  gradeName: string | null,//年级名称
  provinceName: string | null,//地址省份名称
  cityName: string | null,//地址城市名称
  countyName: string | null,//地址区域名称
  address: string | null,//地址
  house: string | null,//门牌号
  tSex: number | null,//教师性别
  price: number | null,//课酬
  alreadyTeachName: string | null,//已绑定教师
  alreadyTeachId: number | null,//已绑定教师id
  tId: string | number | null,//要绑定或更换的教师id
  checkedTId: Array<string | number> | null,//要绑定或更换的教师id
  hasSend: boolean,//是否已派遣 true：是  false：否
}

//查询条件
const dispatchReplaceSearch = ref({
  name: null,
})
const dispatchReplaceModel = ref<boolean>(false);
const dispatchReplaceModelTitle = ref<string>('教师');
const dispatchHandelSubmitLoading = ref<boolean>(false);
const dispatchReplaceFormRef = ref<FormInst | null>(null);
const dispatchReplaceForm = ref<dispatchReplace>({
  orderId: null,
  orderSn: null,
  userName: null,
  phone: null,
  courseName: null,//课程名称
  classifyName: null,//课程分类名称
  gradeName: null,//年级名称
  provinceName: null,//地址省份名称
  cityName: null,//地址城市名称
  countyName: null,//地址区域名称
  address: null,//地址
  house: null,//门牌号
  tSex: null,//教师性别
  price: null,//课酬
  alreadyTeachName: null,//已绑定教师
  alreadyTeachId: null,//已绑定教师
  tId: null,
  hasSend: false,
  checkedTId: [],
})
const drColumns = ref([
  {
    type: 'selection',
    multiple: false,
    disabled(row: { id: number }) {
      return dispatchReplaceForm.value.alreadyTeachId != null && row.id === dispatchReplaceForm.value.alreadyTeachId
    }
  }, {
    title: '头像',
    key: 'avatar',
    width: 60,
    render(row: { avatar: string }) {
      if (row.avatar) {
        return h(NImage, {
          width: 30,
          height: 30,
          src: Config.VIEW_FILE + row.avatar
        })
      }
    }
  }, {
    title: '姓名',
    key: 'name',
  },{
    title: '性别',
    key: 'sex',
    width: 80,
    render(row: { sex: boolean | number }) {
      const genderText = row.sex == 1 ? '男' :'女' ;
      return h('span', null, {default: () => (genderText)})
    }
  }, {
    title: '电话',
    key: 'phone',
    width: 120,
  }, {
    title: '用户微信',
    key: 'nickName',
    width: 120,
    render(row: { nickName: string, wechatAvtar: string }) {
      return h('div', {style: {width: '100%', display: 'flex'}}, {
        default: () => (
            [
              h(NImage, {width: 30, height: 30, src: Config.VIEW_FILE + row.wechatAvtar}),
              h(NEllipsis, {style: {display: 'block', paddingLeft: '5px'}}, {default: () => (row.nickName)})
            ])
      })
    }
  }
])
const drData = ref([])
//派遣、更换教师
const dispatchReplaceTeacher = (record: Recordable) => {
  getTeacherList();
  dispatchReplaceForm.value.orderId = record.id;
  dispatchReplaceForm.value.orderSn = record.sn;
  dispatchReplaceForm.value.userName = record.userName;
  dispatchReplaceForm.value.phone = record.phone;
  dispatchReplaceForm.value.courseName = record.courseName;
  dispatchReplaceForm.value.classifyName = record.classifyName;
  dispatchReplaceForm.value.gradeName = record.gradeName;
  dispatchReplaceForm.value.provinceName = record.provinceName;
  dispatchReplaceForm.value.cityName = record.cityName;
  dispatchReplaceForm.value.countyName = record.countyName;
  dispatchReplaceForm.value.address = record.address;
  dispatchReplaceForm.value.house = record.house;
  dispatchReplaceForm.value.tSex = record.tsex;
  dispatchReplaceForm.value.price = record.price;
  dispatchReplaceForm.value.hasSend = record.sendTeacher == 1;
  dispatchReplaceForm.value.alreadyTeachName = record.teacher ? record.teacher.name : null;
  dispatchReplaceForm.value.alreadyTeachId = record.teacher ? record.teacher.id : null;
  dispatchReplaceModel.value = true;
}
const closeDispatchReplace = () => {
  dispatchReplaceForm.value.orderId = null;
  dispatchReplaceForm.value.orderSn = null;
  dispatchReplaceForm.value.userName = null;
  dispatchReplaceForm.value.phone = null;
  dispatchReplaceForm.value.courseName = null;
  dispatchReplaceForm.value.classifyName = null;
  dispatchReplaceForm.value.gradeName = null;
  dispatchReplaceForm.value.provinceName = null;
  dispatchReplaceForm.value.cityName = null;
  dispatchReplaceForm.value.countyName = null;
  dispatchReplaceForm.value.address = null;
  dispatchReplaceForm.value.house = null;
  dispatchReplaceForm.value.tSex = null;
  dispatchReplaceForm.value.price = null;
  dispatchReplaceForm.value.hasSend = false;
  dispatchReplaceForm.value.alreadyTeachName = null;
  dispatchReplaceForm.value.alreadyTeachId = null;
  dispatchReplaceForm.value.tId = null;
  dispatchReplaceForm.value.checkedTId = [];
  dispatchReplaceSearch.value.name = null;
  dispatchHandelSubmitLoading.value = false;
}
const checkedTeacherForOrder = (keys: Array<string | number>) => {
  dispatchReplaceForm.value.checkedTId = keys;
  dispatchReplaceForm.value.tId = keys[0];
}
const submitDispatchReplace = (e:MouseEvent) => {
  e.preventDefault();
  if (dispatchReplaceForm.value.tId ==null){
    const msg=dispatchReplaceForm.value.hasSend?'更换':'派遣';
    message.error('请选择需要'+msg+'的教师');
    return false;
  }
  dispatchHandelSubmitLoading.value=true;
  postPutRequest('order/send_teacher_order',dispatchReplaceForm.value,'POST').then((res:ResponseResult)=>{
    if (res.code === 200) {
      message.success(res.message, {
        duration: 1500,
        onLeave() {
          dispatchReplaceModel.value = false;
          data_list.value.reload();
        }
      })
    } else {
      message.error(res.message);
      dispatchHandelSubmitLoading.value = false;
    }
  })
}
//切换订单状态
const handelSelectSearchStatus = (payStatus: number | null, status: number | null) => {
  search_param.value.payStatus = payStatus;
  search_param.value.status = status;
  handleSubmitSearch();
}
//切换订单状态
const handelSelectSearchTime = (value: string | number | undefined | any) => {
  console.log(value)
  orderTime.value = value;
  if (value == null) {
    search_param.value.start = null;
    search_param.value.end = null;
  } else {
    if (value == 'today') {
      search_param.value.start = DateFns.today();
      search_param.value.end = null;
    } else if (value == 'yesterday') {
      search_param.value.start = DateFns.yesterday();
      search_param.value.end = null;
    } else {
      let dates: Array<String> = [];
      if (value == '7days') {
        dates = DateFns.last7Days();
      }
      if (value == '30days') {
        dates = DateFns.last30Days();
      }
      if (value == 'month') {
        dates = DateFns.currentMonth();
      }
      if (value == 'year') {
        dates = DateFns.currentYear();
      }
      search_param.value.start = dates[0];
      search_param.value.end = dates[1];
    }
  }
  if (value != 'other') {
    handleSubmitSearch();
  }
}
const handelCustomDate = (value: number | [number, number]) => {
  search_param.value.start = DateFns.ttConversion(value[0]);
  search_param.value.end = DateFns.ttConversion(value[1]);
  handleSubmitSearch();
}
watch(() => addEditForm.value.day, (to) => {
  addEditForm.value.res = to && to.length > 0 ? 1 : 0;
})

//查询
const handleSubmitSearch = () => {
  console.log(search_param.value)
  data_list.value.searchListData();
}
//修改订单
const handleEdit = (record: Recordable) => {
  getCourse(record.grade);
  getCityOption(record.province)//地区
  getCountyOption(record.city)//地区
  addEditForm.value.id = record.id;
  addEditForm.value.sn = record.sn;
  addEditForm.value.userId = record.userId;
  addEditForm.value.userName = record.userName;
  addEditForm.value.phone = record.phone;
  addEditForm.value.sex = record.sex;
  addEditForm.value.grade = record.grade;
  addEditForm.value.courseId = record.courseId;
  addEditForm.value.price = record.price;
  addEditForm.value.province = record.province;
  addEditForm.value.city = record.city;
  addEditForm.value.county = record.county;
  addEditForm.value.address = record.address;
  addEditForm.value.house = record.house;
  addEditForm.value.situation = record.situation ? record.situation : null;
  addEditForm.value.tSex = record.tsex;
  addEditForm.value.tSituation = record.tSituation ? record.tSituation : null;
  addEditForm.value.payStatus = record.payStatus;
  addEditForm.value.res = record.res;
  addEditForm.value.status = record.status;
  addEditForm.value.appTime = record.appTime ? record.appTime : null;
  addEditForm.value.totalTime = record.totalTime ? record.totalTime : null;
  addEditForm.value.day = record.dayData ? record.dayData : null;
  addEditModel.value = true;
}
//删除订单
const handleDelete = (record: Recordable) => {
  delRequest('order/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//重置查询条件
const handleResetSearch = () => {
  search_param.value.key = null;
  search_param.value.status = null;
  search_param.value.payStatus = null;
  search_param.value.start = null;
  search_param.value.end = null;
  handleSubmitSearch();
}
//关闭新增、修改订单
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.userName = null;
  addEditForm.value.userId = null;

  addEditForm.value.phone = null;
  addEditForm.value.province = null;
  addEditForm.value.city = null;
  addEditForm.value.county = null;
  addEditForm.value.address = '';
  addEditForm.value.res = 0;
  addEditForm.value.day = null;
  addEditForm.value.status = 0;
  addEditForm.value.sex = null;
  addEditForm.value.grade = null;
  addEditForm.value.gradeName = null;
  addEditForm.value.courseId = null;
  addEditForm.value.courseName = null;
  addEditForm.value.classifyName = null;
  addEditForm.value.provinceName = null;
  addEditForm.value.cityName = null;
  addEditForm.value.countyName = null;
  addEditForm.value.house = '';
  addEditForm.value.payStatus = 0;
  addEditForm.value.tSex = 1;
  addEditForm.value.price = null;
  addEditForm.value.situation = null;
  addEditForm.value.tSituation = null;
  addEditForm.value.appTime = null;
  addEditForm.value.totalTime = null;
  addEditForm.value.remainder = null;
  handelSubmitLoading.value = false;
}
const renderUserLabel = (option: SelectOption) => {
  return h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      },
      [
        h(NAvatar, {
          src: Config.VIEW_FILE + option.avatar,
          round: true,
          size: 'small'
        }),
        h(
            'div',
            {
              style: {
                marginLeft: '12px',
                padding: '4px 0'
              }
            },
            [
              h('div', null, [option.label as string]),
              h(
                  NText,
                  {depth: 3, tag: 'div'},
                  {
                    default: () => 'ID:' + option.value
                  }
              )
            ]
        )
      ]
  )
}
const renderSingleSelectTag = ({option}) => {
  return h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      },
      [
        h(NAvatar, {
          src: Config.VIEW_FILE + option.avatar,
          round: true,
          size: 24,
          style: {
            marginRight: '12px'
          }
        }),
        option.label as string
      ]
  )
}
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'order/edit' : 'order/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
//选择省份获取地区数据
const getCityOption = (value: number) => {
  if (value) {
    const city: CascaderOption | any = reginData.value.find(item => item.value === value);
    const cityOp = city.children.map((item: any): CascaderOption => ({
      label: item.label,
      value: item.value
    }));
    cityOptions.value = cityOp;
    addEditForm.value.city = null;
    addEditForm.value.county = null;
    countyOptions.value = [];
  } else {
    addEditForm.value.city = null;
    addEditForm.value.county = null;
    cityOptions.value = [];
    countyOptions.value = [];
  }
}
const getCountyOption = (value: number | null) => {
  if (value) {
    const county = findChildrenByValue(reginData.value, value);
    addEditForm.value.county = null;
    countyOptions.value = county;
  } else {
    addEditForm.value.county = null;
    countyOptions.value = [];
  }
}
const findChildrenByValue = (data: CascaderOption[], value: number): SelectOption[] | undefined => {
  for (const item of data) {
    if (item.value === value) {
      return item.children;
    }
    if (item.children) {
      const found = findChildrenByValue(item.children, value);
      if (found) {
        return found;
      }
    }
  }
  return undefined;
}
const getUser = async () => {
  await getRequest('user/get_select').then((result: ResponseResult) => {
    const {data} = result;
    usersOptions.value = data;
  })
}
//获取区域数据
const getRegin = async () => {
  await getRequest('region/get_tree').then((result: ResponseResult) => {
    const {data} = result;
    reginData.value = convertRegin(data);
  })
}
//处理区域数据
const convertRegin = (data: TreeSelectOption[]) => {
  return data.map((item): CascaderOption => ({
    label: item.label,
    value: item.key,
    ...(item.children && item.children.length > 0 && {children: convertRegin(item.children)}),
  }));
}
// 年级
const getGrade = async () => {
  await getRequest("grade/select").then((result: ResponseResult) => {
    const {data} = result;
    gradeOption.value = data;
  })
}
//获取科目
const getCourse = (value: number | null) => {
  addEditForm.value.courseId = null;
  if (value != null) {
    getRequest("course/get_course_grade", {gid: value}, true).then((result: ResponseResult) => {
      const {data} = result;
      courseOption.value = data;
    })
  } else {
    courseOption.value = [];
  }
}
//获取订单派遣的教师
const getTeacherList = async () => {
  await getRequest('teacher/get_teach', dispatchReplaceSearch.value).then((res: ResponseResult) => {
    const {data} = res;
    drData.value = data;
  })
}

onBeforeMount(() => {
  getRegin();
  getUser();
  getGrade();
})
</script>

<style scoped lang="scss">

</style>